package com.qf.smsplatform.strategy.service.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.service.Strategy;
import com.qf.smsplatform.strategy.service.api.CacheService;
import com.qf.smsplatform.strategy.utils.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: LeeRui
 * 2021/1/27 下午 9:18
 * 扣费策略
 **/
@Service(value = "fee")
@Slf4j
public class FeeStrategy implements Strategy {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("【扣费策略】 扣费策略开始执行！！！");
        //Redis缓存中获取客户余额
        Long freeFee = Long.parseLong(cacheService.hget(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(), "fee"));
        //查询本次短信需要扣的费用
        long fee = standardSubmit.getFee();
        //判断余额是否充足
        if (freeFee>=fee){
            //余额充足，则扣费
            Long koufei = cacheService.hincr(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(), "fee", -fee);
            System.out.println("客户剩余费用："+koufei);

            //扣费成功后只是临时将用户费用扣除进行冻结，若运营商真正发送成功短信后再真正扣除费用，否则还要将冻结的费用回滚回用户fee
            //将费用临时冻结存储到缓存  key为CUSTUMER_FEE+客户ID  value为本次冻结费用
            cacheService.hincr(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE+standardSubmit.getClientID(),"fee", fee);
            //记录冻结日志
            log.info("【策略模块】 冻结扣费成功，扣费策略执行成功！！！");
            return true;
        }

        //余额不足，记录日志并发送两天消息到MQ指定队列(ES需要存的日志和给客户推送的报告)
        log.info("【策略模块】 余额不足，扣费策略执行失败！！！");
        //向MQ发送消息
        pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
        pushMsgUtil.pushReport(standardSubmit,StrategyConstants.STRATEGY_ERROR_FEE);
        return false;
    }
}
